<!--
 * @Description: In User Settings Edit
 * @Author: Blue
 * @Date: 2019-10-15 16:18:48
 * @LastEditTime: 2019-10-15 19:35:16
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div id="preview">
    <div class="box" :style="objstyle" ref="box" @mouseenter="handleMouse" @mousemove="handleMove">
      <program :program-style="programStyle"></program>
      <img :src="imgUrl" alt="">
    </div>
  </div>
</template>
<script>
  import program from './program.vue'

  export default {
    name: "preview",
    props: {
      // 自定义样式
      objstyle: {
        type: Object,
      },
      // 即时预览数据
      datas: {
        type: Object,
        required: true
      },
      // 图片实体数据，通过父组件请求数据传递
      itemData: {
        type: Object,
        required: true
      }
    },
    components: {
      program
    },
    data() {
      return {
        // 鼠标相对盒子x坐标
        x: 0,
        // 盒子宽度
        divW: 0,
        // 子组件设置图片
        imgUrl: "",
        // 进度条进度属性
        programStyle: {
          width: ''
        }
      }
    },
    computed: {

    },
    mounted() {
      // console.log(this.datas)
      this.imgUrl = this.itemData.picture
    },
    methods: {
      /**
       * @description: 鼠标第一次移入 
       * @param {type} 
       * @return: void
       */
      handleMouse(e) {
        const length = Object.keys(this.datas).length
        console.log(length)
        if (length === 0) {
          this.$emit('get-img', this.itemData)
        }
        // 记录第一次鼠标x位置
        this.x = e.offsetX
        // 记录盒子宽度
        this.divW = this.$refs.box.offsetWidth
      },
      /**
       * @description: 鼠标在盒内移动
       * @param {type} 
       * @return: void
       */
      handleMove(e) {
        // 每次移动记录鼠标x坐标
        this.x = e.offsetX;
        // 遍历预览数据，找出包含x坐标的范围，获取图片
        for (let key in this.datas) {
          if (this.x > this.datas[key][0] && this.x < this.datas[key][1]) {
            console.log(this.x, key)
            this.imgUrl = `/static/${key}`
          }
        }
        this.programControl(this.x)
      },
      /**
       * @description: 进度条控制
       * @param {type} 
       * @return: void
       */
      programControl(x) {
        this.programStyle.width = `${x}px`
      }
    },
  }

</script>

<style lang="scss">
  .box {
    width: 200px;
    height: 100px;
    background: #ddd;
    border-radius: 4px;
    position: relative
  }

  img {
    width: 100%;
    height: 100%;
  }

</style>
